package ru.urfc.portal.ui.client.googlets.email;

import ru.urfc.portal.ui.client.BaseGooglet;
import ru.urfc.portal.ui.client.Style;
import ru.urfc.portal.ui.client.Utils;
import ru.urfc.portal.ui.client.controllers.ItemsController;
import ru.urfc.portal.ui.client.controllers.SimpleItemsController;
import ru.urfc.portal.ui.client.controllers.events.PostEvent;
import ru.urfc.portal.ui.client.descriptor.GridDescriptor;

import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Widget;

public class AdminAssociate extends BaseGooglet {

	interface Binder extends UiBinder<Widget, AdminAssociate> {}
	private static Binder binder = GWT.create(Binder.class);
	
	@UiField Style style;
	@UiField Element email;
	@UiField TextField<String> key;
	
	@UiField Anchor anchor;
	@UiField Element shortView;
	@UiField Element fullView;

	public Type<ItemsController> ASSOCIATE = new Type<ItemsController>();

	@UiHandler("associate")
	void associate(ClickEvent e) {
		getEventsDispatcher().fireEvent(new PostEvent(ASSOCIATE));
	}

	@Override
	protected void init() {
		initWidget(binder.createAndBindUi(this));
		Utils.hide(fullView);
		anchor.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Utils.hide(shortView);
				Utils.show(fullView);
			}
		});
		
		email.setInnerText(getProperty(GOOGLET_PARAMETER_EMAIL));
		
		GridDescriptor descriptor = new GridDescriptor(ASSOCIATION_KEY, USER_ASSOCIATIONS);
		descriptor.addTextField("email", email).setEditable();
		descriptor.addTextField("key", key);
		
		register(ASSOCIATE, new SimpleItemsController(descriptor) {
			@Override
			public void onUpdate(Object data) {
				if (data.equals(HTTP_NO_CONTENT)) {
					redirect(PAGE_ASSOCIATED_USERS);
				} else if (data.equals(INVALID_ASSOCIATION_KEY)) {
					MessageBox.alert("Внимание", "Введен неверный код", null);
				}
			}
		});
	}

}